package com.keta.generate.core;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import com.fly.code.GraphicalRun;
import com.keta.generate.util.FreeMarkers;
import com.keta.generate.util.Resources;
import com.keta.generate.util.StringUtil;
import com.keta.generate.vo.Column;
import com.keta.generate.vo.Table;

import freemarker.template.Template;

public class GenerateCode extends AbstractGenerate implements Generate
{
    
    public GenerateCode()
    {
        super();
    }
    
    /**
     * 生成代码
     * 
     * @param table
     */
    @Override
    public void generate(Table table)
    {
        generateJava(table);
    }
    
    /**
     * 生成java代码
     * 
     * @param table
     * @see [类、类#方法、类#成员]
     */
    private void generateJava(Table table)
    {
        try
        {
            // 特殊类型处理
            handleSpecial(table.getColumns());
            model.put("tableName", table.getTableName().toLowerCase());
            model.put("columns", table.getColumns());
            model.put("indexName", "indexName");// for SpringJpa jsp
            model.put("pk", table.getPk());
            model.put("date", new Date());
            model.put("requestMapping", "demo/" + StringUtil.camelCase(table.getTableName(), false).toLowerCase());
            model.put("functionName", "表" + table.getTableName() + "数据");
            
            URL url = GraphicalRun.class.getProtectionDomain().getCodeSource().getLocation();
            if (url.getPath().endsWith(".jar")) // 可运行jar内文件处理
            {
                JarFile jarFile = new JarFile(url.getFile());
                Enumeration<JarEntry> entrys = jarFile.entries();
                while (entrys.hasMoreElements())
                {
                    JarEntry jar = (JarEntry)entrys.nextElement();
                    String name = jar.getName();
                    if (!jar.isDirectory() && name.startsWith("template/" + Resources.TPL_FILE_DIR))
                    {
                        String path = FreeMarkers.renderString(name, model);
                        String realPath = javaPath + StringUtils.substringAfter(path, "template/" + Resources.TPL_FILE_DIR);
                        if (name.endsWith(".ftl"))// 模板文件
                        {
                            realPath = realPath.substring(0, realPath.length() - 4);
                            String ftl = StringUtils.substringAfter(name, "template/" + Resources.TPL_FILE_DIR + "/");
                            Template template = config.getTemplate(ftl);
                            String content = FreeMarkers.renderTemplate(template, model);
                            FileUtils.writeStringToFile(new File(realPath), content, "UTF-8");
                        }
                        else
                        {
                            InputStream inputStream = GraphicalRun.class.getResourceAsStream("/" + name);
                            FileUtils.copyInputStreamToFile(inputStream, new File(realPath));
                        }
                    }
                }
            }
            else
            {
                File tFile = new File(url.getFile() + "/template/" + Resources.TPL_FILE_DIR);
                Collection<File> listFiles = FileUtils.listFiles(tFile, new String[] {"jar", "xml", "ftl", "jsp", "html", "htm", "js", "css", "map", "eot", "svg", "ttf", "woff", "woff2"}, true);
                for (File file : listFiles)
                {
                    String path = FreeMarkers.renderString(file.getAbsolutePath(), model);
                    String realPath = javaPath + StringUtils.substringAfter(path, "\\template\\" + Resources.TPL_FILE_DIR + "\\");
                    if (realPath.endsWith(".ftl"))
                    {
                        realPath = realPath.substring(0, realPath.length() - 4);
                        String ftl = StringUtils.substringAfter(file.getAbsolutePath(), "\\template\\" + Resources.TPL_FILE_DIR + "\\");
                        Template template = config.getTemplate(ftl);
                        String content = FreeMarkers.renderTemplate(template, model);
                        FileUtils.writeStringToFile(new File(realPath), content, "UTF-8");
                    }
                    else
                    {
                        FileUtils.copyFile(file, new File(realPath));
                    }
                }
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
    
    @Override
    public void generate(List<Table> tables)
        throws Exception
    {
    }
    
    /**
     * 特殊类型处理
     * 
     * @param columns
     */
    private void handleSpecial(List<Column> columns)
    {
        boolean hasDate = false;
        boolean hasBigDecimal = false;
        for (Column column : columns)
        {
            if (column.getJavaType().equals("Date"))
            {
                hasDate = true;
            }
            else if (column.getJavaType().equals("BigDecimal"))
            {
                hasBigDecimal = true;
            }
        }
        model.put("hasDate", hasDate);
        model.put("hasBigDecimal", hasBigDecimal);
    }
}
